package com.rest.demo.jdbcdemo.controller;

import com.rest.demo.jdbcdemo.entity.UserPo;
import com.rest.demo.jdbcdemo.service.IUserService;
import com.rest.demo.response.ResponseEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author Administrator
 * @decription
 * @Date 2017-11-14 14:49
 */
@RestController
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private IUserService userService;

    @GetMapping(value = "/userPo")
    public ResponseEntity findAllUser() {
        List<UserPo> userPoList = userService.finaAllUser();
        return new ResponseEntity().success(userPoList);
    }

    @GetMapping(value = "/userPo/{id}")
    public ResponseEntity findUserById(@PathVariable("id") Integer id) {
        UserPo userPo = userService.findUserById(id);
        return new ResponseEntity().success(userPo);
    }

    @PostMapping(value = "/userPo")
    public ResponseEntity addUser(@RequestBody @Valid UserPo user) {
        int result = userService.saveUser(user);
        if(result == 0) {
            return new ResponseEntity().failure("save user failed");
        }
        return new ResponseEntity().success();
    }

    @PutMapping(value = "/userPo/{id}")
    public ResponseEntity updateUser(@PathVariable("id") Integer id,@RequestBody @Valid UserPo user) {
        user.setUserId(id);
        int count = userService.updateUser(user);
        if(count != 1) {
            return new ResponseEntity().failure("update failed");
        }
        return new ResponseEntity().success();
    }

    @DeleteMapping(value = "/userPo/{id}")
    public ResponseEntity deleteUser(@PathVariable("id") Integer id) {
        int count = userService.deleteUser(id);
        if(count != 1) {
            return new ResponseEntity().failure("delete failed");
        }
        return new ResponseEntity().success();
    }
}
